﻿using AutoMapper;
using BasehInfoManager_IDal;
using BasehInfoManagerModel;
using BasehInfoManagerViewModel;
using BasehInfoManagerViewModel.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using zy_11_10.Common.Lib.TypeTools;

namespace BaseInfoManagerDal
{
    public class RoleDbDal : BaseDal,IRoleDbDal
    {



        //注入上下文
        public RoleDbDal(ManagerDbContext managerDbContext):base(managerDbContext)
        {
           

        }
       
        #region 角色显示
        //角色显示的分页
        public PagerResult<RoleDb> Searchpage(SearchModel searchModel)
        {
            var query = _managerDbContext.RoleDb.AsQueryable();
            //判断有没有搜索条件
            if (searchModel.SearchItem != null && searchModel.SearchItem.Count > 0)
            {
                //把搜索条件取出来
                var tempDi = searchModel.SearchItem;
                //搜索字段为role_name
                string roleName = "role_name";
                //判断搜索搜索条件中是否有role_name
                if (tempDi.Keys.Contains(roleName) && !string.IsNullOrEmpty(tempDi[roleName]))
                {
                    query = query.Where(c => c.role_name.Contains(tempDi[roleName]));
                }
                //搜索条件(角色状态)
                string roleStatus = "role_status";
                if (tempDi.Keys.Contains(roleStatus) && !string.IsNullOrEmpty(tempDi[roleStatus]))
                {
                    int tempStatus = -1;
                    if (int.TryParse(tempDi[roleStatus], out tempStatus))
                    {
                        query = query.Where(c => c.role_status == tempStatus);
                    }
                }
                if (!string.IsNullOrEmpty(searchModel.OrderBy))
                {
                    if (searchModel.OrderBy == "role_id")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.role_id);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.role_id);
                        }
                    }
                    //以名称排序
                    if (searchModel.OrderBy == "role_name")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.role_name);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.role_name);
                        }
                    }
                }
            }

            //调用封装分页
            return BasePageSearch(query, searchModel);
            
        }
        #endregion

        #region 角色添加
        //角色添加
        public int RoleDbAdd(RoleDbView view)
        {
            //创建事物
            using (var tran = _managerDbContext.Database.BeginTransaction())
            {
                try
                {
                    RoleDb db = ModelCopier.CreateInstanceFrom<RoleDb>(view);
                    _managerDbContext.RoleDb.Add(db);
                    //保存后获取role_id
                    _managerDbContext.SaveChanges();
                    List<RoleModuleRelation> rmrs = new List<RoleModuleRelation>();
                    if (view.roleModuleCode != null && view.roleModuleCode.Count > 0)
                    {
                        foreach (var mc in view.roleModuleCode)
                        {
                            rmrs.Add(new RoleModuleRelation()
                            {
                                role_id = db.role_id,
                                module_code = mc,
                                creator_date = db.creator_date,
                                creator_name = db.creator_name
                            });



                        }
                        _managerDbContext.RoleModuleRelation.AddRange(rmrs);
                        _managerDbContext.SaveChanges();
                    }
                    tran.Commit();
                    return db.role_id;
                }
                catch (Exception e)
                {

                    throw;
                    throw e;
                }
            }
        }
        #endregion

        #region 角色反填
        //角色反填
        public RoleDbView GetRoleViewById(int roleId)
        {
            var roleDb = _managerDbContext.RoleDb.FirstOrDefault(a => a.role_id == roleId);

            if (roleDb == null) return null;
            RoleDbView view = ModelCopier.CreateInstanceFrom<RoleDbView>(roleDb);
            view.roleModuleCode = _managerDbContext.RoleModuleRelation.Where(a => a.role_id == roleId).Select(a => a.module_code).ToList();
            return view;
        }
        #endregion

        #region 角色修改
        //要先删除角色模块表，再添加新的角色模块表
        public bool RoleUpdate(RoleDbView view)
        {
            using (var tran = _managerDbContext.Database.BeginTransaction())
            {
                try
                {
                    var roleDb = _managerDbContext.RoleDb.FirstOrDefault(a => a.role_id == view.role_id);

                    ModelCopier.CopyModel(view, roleDb, "creator_name", "creator_date");
                    //保存
                    _managerDbContext.SaveChanges();
                    string delSql = "delete role_module_relation where role_id=({0})";
                    //删除Sql
                    _managerDbContext.Database.ExecuteSqlRaw(delSql, roleDb.role_id);

                    List<RoleModuleRelation> rmrs = new List<RoleModuleRelation>();
                    if (view.roleModuleCode != null && view.roleModuleCode.Count > 0)
                    {
                        foreach (var mc in view.roleModuleCode)
                        {
                            rmrs.Add(new RoleModuleRelation()
                            {
                                role_id = roleDb.role_id,
                                module_code = mc,
                                creator_date = roleDb.modifi_date.Value,
                                creator_name = roleDb.modifi_name
                            });

                        }
                        _managerDbContext.RoleModuleRelation.AddRange(rmrs);
                        _managerDbContext.SaveChanges();



                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception a)
                {
                    tran.Rollback();
                    throw a;

                }
            }
        }
        #endregion
    }
}

